package com.dys.hejiayuncommunity.web.test;

import com.dys.hejiayuncommunity.common.core.domain.BaseResponse;
import com.dys.hejiayuncommunity.common.core.exception.BaseException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @className: com.dys.hejiayuncommunity.web.test.UserController
 * @description: com.dys.hejiayuncommunity.web.test
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/12/02 22:04
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @GetMapping(value = "/findUserById")
    public BaseResponse<User> findUserById(String userId) {
        if (userId != null) {
            return BaseResponse.success(new User(userId, "王大锤"));
        } else {
            return BaseResponse.failed("查询用户信息失败");
        }
    }

    @RequestMapping(value = "/addUser")
    public BaseResponse<String> addUser(@Validated User user, BindingResult bindingResult) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        // 如果参数校验失败，会将错误信息封装成对象组装在 BindingResult
        if (!fieldErrors.isEmpty()) {
            return BaseResponse.failed(fieldErrors.get(0).getDefaultMessage());
        }
        return BaseResponse.success("添加成功");
    }

    @RequestMapping(value = "/findUser")
    public BaseResponse<String> findUser() {
        throw new BaseException("500", "模拟自定义异常");
    }
}
